package com.three.iot.rest.utils;

import com.alibaba.fastjson.JSON;
import com.three.iot.api.DataStoreService;
import com.three.iot.commons.po.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

@Component
public class RequestUtils {

    @Autowired
    private DataStoreService dataStore;

    private static DataStoreService dataStoreService;

    @PostConstruct
    private void init() {
        this.dataStoreService = dataStore;
    }

    public static UserInfo getCurrentUser(HttpServletRequest request) {
        String tokenStr = request.getHeader("Authorization");
        String userJson = (dataStoreService.getVal(tokenStr));
        UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
        return userInfo;
    }

    public static String getCurrentUserNo(HttpServletRequest request) {
        UserInfo userInfo = getCurrentUser(request);
        if (userInfo != null) {
            return userInfo.getUserNo();
        }
        return null;
    }

    public static String getCurrentUserName(HttpServletRequest request) {
        UserInfo userInfo = getCurrentUser(request);
        if (userInfo != null) {
            return userInfo.getNickName();
        }
        return null;
    }

}
